package com.ty.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ty.util.ExcelUtils;

@Controller
@RequestMapping("/test")
public class TestController {

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String listpre() {
		//log.info("测试日志访问********start*************11111");
		System.out.println("*************");
		//log.info("测试日志访问********end*************11111");
		return "/background/classchange/list";
		
	}
	@RequestMapping(value = "/test", method = RequestMethod.GET)
	public void getExcel(HttpServletResponse response , HttpServletRequest request) {
		System.out.println("*************");
		List<Map<String,String>> dataList = new ArrayList<Map<String,String>>();
		for(int i=0 ; i<100;i++) {
			Map<String,String> map = new HashMap<String,String>();
			map.put("userId", String.valueOf(i));
			map.put("viewLength", String.format("%.2f", Math.random()*1000));
			dataList.add(map);
		}		
		
		OutputStream outStream = null;
		try {			
			String headStr = "用户ID,观看时长";
			String cellSize = "50,40";
			String name = "userId,viewLength";
			Map<String,Object> params = new HashMap<String,Object>();
			params.put("dataList", dataList);
			params.put("excel_head_cnname", headStr);
			params.put("excel_data_cellSize", cellSize);
			params.put("excel_data_enname", name);

			outStream = response.getOutputStream();
        
			String fileName = "aa.xls";
			setResponseFileName(false, response, fileName);
			
			ExcelUtils.createExcel2007(outStream, params);
			
			outStream.flush();
			
			outStream.close();

			response.flushBuffer();
			
		}catch (Exception e) {		
			
		}
		System.out.println("*******end******");
	}
	
	public void setResponseFileName(boolean isIE, HttpServletResponse response, String displayName) throws Exception  {
		String dspName;
		String dspNameNew;
		if (isIE) {
			dspName = URLEncoder.encode(displayName, "UTF-8");
			dspNameNew = dspName.replaceAll("\\+", "%20");// 修正URLEncoder将空格转换成+号的BUG
			response.setHeader("Content-Disposition", "attachment;filename=" + dspNameNew);
		} else {
			dspNameNew = new String(displayName.getBytes("UTF-8"), "ISO8859-1");
			response.setHeader("Content-Disposition","attachment;filename=\"" + dspNameNew + "\"");// firefox空格截断
		}
	}
	
}
